package com.hy.mydesktop.client.mvc.desktop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import com.extjs.gxt.desktop.client.Desktop;
import com.extjs.gxt.desktop.client.Shortcut;
import com.extjs.gxt.desktop.client.StartMenu;
import com.extjs.gxt.desktop.client.TaskBar;
import com.extjs.gxt.samples.resources.client.TestData;
import com.extjs.gxt.samples.resources.client.model.Stock;
import com.extjs.gxt.ui.client.Registry;

import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.MenuEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.store.GroupingStore;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ToolButton;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridGroupRenderer;
import com.extjs.gxt.ui.client.widget.grid.GroupColumnData;
import com.extjs.gxt.ui.client.widget.grid.GroupingView;
import com.extjs.gxt.ui.client.widget.layout.AccordionLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.menu.MenuItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.HasWidgets;
import com.hy.mydesktop.client.component.event.AppEvents;
import com.hy.mydesktop.client.component.factory.GxtDesktopComponentFactory;
import com.hy.mydesktop.client.component.mvc.event.EventStructureMetaModel;
import com.hy.mydesktop.client.mvc.base.BaseController;
import com.hy.mydesktop.client.mvc.base.BaseDisplay;
import com.hy.mydesktop.client.mvc.base.BasePresenterAndView;
import com.hy.mydesktop.client.mvc.base.Presenter;
import com.hy.mydesktop.client.mvc.logindialog.LoginDialog;
import com.hy.mydesktop.shared.persistence.domain.gxt.GxtComponentMetaNodeModel;
import com.hy.mydesktop.shared.util.log.MyLoggerUtil;



public class ShortcutPresenter  extends BasePresenterAndView{
	
	private Desktop desktop = null;
	
	private Shortcut shortcut = null;
	public interface Display extends BaseDisplay{
		public Button getLoginButton() ;
		public TextField<String> getUserNameTextField() ;
		public TextField<String> getPasswordTextField() ;
		public LoginDialog getLoginDialog() ;
		public void show();


	}
	private Display display;
	public Shortcut getShortcut() {
		return shortcut;
	}

	public void setShortcut(Shortcut shortcut) {
		this.shortcut = shortcut;
	}

	public ShortcutPresenter(Controller controller,Display display) {
		super(controller);
		this.display = display;
		MyLoggerUtil.printPresenterDebugForInit(getClass());

		
	}

	@Override
	protected void handleEvent(AppEvent event) {
		if (desktop==null) {
			//desktop = (Desktop)map.get("desktop");
			desktop = Registry.get("desktop");
		}
		
		//读取事件中的所有数据信息
		 Map<String, Object> map = event.getData();
		 /**
		  * 触发AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER事件
		  * 根据((BaseController)this.getController()).getViewData()  获取视图的标识
		  * 创建并初始化视图
		  */
		//0002
		if (AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER==event.getType()) {
//			GxtComponentMetaModel data = (GxtComponentMetaModel)map.get("gxtComponentMetaModel");
			 /**
			 * data 可以是需要加载的菜单的元模型信息
			 *     也可以是用户信息，调用后台业务逻辑，获得需要加载的菜单的元模型信息
			 */
			 
		    //添加一个快捷方式
			desktop = (Desktop)map.get("desktop");
			
			String viewDataCode=((BaseController)this.getController()).getViewData();
			GxtComponentMetaNodeModel gxtComponentMetaNodeModel = null;
			if (viewDataCode!=null) {
				/**
				 * 调用后台业务逻辑，获得viewDataCode，对应的元模型
				 */
				System.out.println("viewDataCode代码是："+viewDataCode+"执行getGxtComponentMetaNodeModel ()");
				gxtComponentMetaNodeModel = ((BaseController)(this.getController())).getGxtComponentMetaNodeModel();

				/*if (viewDataCode.equals("shortcut_viewData_init_01")) {
					//gxtComponentMetaNodeModel = this.getGxtComponentMetaNodeModel();
					gxtComponentMetaNodeModel = ((BaseController)(this.getController())).getGxtComponentMetaNodeModel();

				}
				
				if (viewDataCode.equals("shortcut_viewData_init_03")) {
					gxtComponentMetaNodeModel = this.getGxtComponentMetaNodeModel2();
				}*/
			}
			/**
			 * 三个参数
			 * 两个参数，一个返回值
			 */
			shortcut = (Shortcut)GxtDesktopComponentFactory.addOneGxtComponentToDesktop( gxtComponentMetaNodeModel);
			
		};
		
		//0003
		if (AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT==event.getType()) {
			
			 EventStructureMetaModel eventstructuremetamodel = 
				 (EventStructureMetaModel)map.get("eventstructuremetamodel");
			 TaskBar taskBar = desktop.getTaskBar();
			 StartMenu startMenu = taskBar.getStartMenu();
			 startMenu.setIconStyle("user");
			 startMenu.setHeading("The StartMenu");
						
			if (shortcut!=null) {
				String responseModeId = eventstructuremetamodel.getResponseModeId();
				/**
				 * responseModeId标识，调用后台业务逻辑
				 * 触发，初始化某一窗口的事件
				 * 返回一个创建好的窗口
				 * 
				 */
				//if (responseModeId.equals("00_01_02")) {
					
					 //shortcut 和与之对应的 Window是一一对应的				
					if (true||shortcut.getData("window")==null) {
						
						// Dispatcher.forwardEvent(AppEvents.DESKTOP_APPLICATION_INIT,map);
						//读取控件的元数据中，关于转发事件的数据
						/**
						 * 元数据中包含的事件方面的数据有两类：
						 * registereventtypes（控件需要响应--监听的事件代码，和，触发事件后需要发送的数据）
						 * dispachereventtypes（在某种条件下，控件需要转发的事件的事件代码，和，转发事件所需要发送的数据）
						 */
						Map<String, Object>	dispachereventtypes =((BaseController)(this.getController())).getGxtComponentMetaNodeModel().get("dispachereventtypes");
						//Map<String, Object>	dispachereventtypes =shortcut.getData("dispachereventtypes");
						Map<String, Object> map2= new HashMap<String, Object>();
					 	/**
					 	 * map2 = map;
					 	 * 这是错误做法
					 	 */
					 	map2 = (Map<String, Object>)((HashMap<String, Object>)map).clone();
					 	
					 	Map<String, Object>	oneDispacherEventTypeData = (Map<String, Object>)dispachereventtypes.get(((String)(map2.get("dispachereventtype"))));
				    	map2.putAll(oneDispacherEventTypeData);
					 	//map2.put("count", 7);
				    	//EventStructureMetaModel eventstructuremetamodel2 = new EventStructureMetaModel();
				    	//eventstructuremetamodel2.setControllerId("windowController");
				    	//eventstructuremetamodel2.setRootControllerId("windowController");
				    	//map2.put("eventstructuremetamodel", eventstructuremetamodel2);
				    	//需要把Desktop传递给下一个事件
				    	map2.put("desktop", desktop);
				    	//TODO 需要把存放Window的容器，传到下一个事件中
				    	map2.put("windowContainer", shortcut);
				    	
				    	
				    	Dispatcher.get().dispatch(AppEvents.DESKTOP_WINDOWAPPLICATION_INIT,map2);
						
						/*Map<String, Object> map2= new HashMap<String, Object>();
						 	*//**
						 	 * map2 = map;
						 	 * 这是错误做法
						 	 *//*
						 	map2 = (Map<String, Object>)((HashMap<String, Object>)map).clone();
					    	map2.put("count", 7);
					    	EventStructureMetaModel eventstructuremetamodel2 = new EventStructureMetaModel();
					    	eventstructuremetamodel2.setControllerId("windowController");
					    	eventstructuremetamodel2.setRootControllerId("windowController");
					    	map2.put("eventstructuremetamodel", eventstructuremetamodel2);
					    	//需要把Desktop传递给下一个事件
					    	map2.put("desktop", desktop);
					    	//需要把存放Window的容器，传到下一个事件中
					    	map2.put("windowContainer", shortcut);
					    	
					    	//  dispatcher.dispatch(AppEvents.DESKTOP_APPLICATION_INIT,map);
					    	*//**
					    	 * 如何解决多个事件之间的数据交互
					    	 * 即，在一个事件的执行过程中，又触发了另一个事件，
					    	 *//*
					    	Dispatcher.get().dispatch(AppEvents.DESKTOP_APPLICATION_INIT,map2);*/
					    	
					    	
					    	/*Window window = createGridWindow();
							shortcut.setData("window", window);*/
					    	
					}
					/*Window ww = shortcut.getData("window");
					if (!desktop.getWindows().contains(ww)) {
					     desktop.addWindow(ww);
					}
					if (ww != null && !ww.isVisible()) {
					    	ww.show();
					} else {
					    	ww.toFront();
					}*/
					
				//} 
				/*if (responseModeId.equals("00_02_02")) {
					//shortcut 和与之对应的 Window是一一对应的			
					if (shortcut.getData("window")==null) {
						Window window = createGridWindow2();
						shortcut.setData("window", window);
						
					}
					Window ww = shortcut.getData("window");
					if (!desktop.getWindows().contains(ww)) {
					      desktop.addWindow(ww);
					    }
					    if (ww != null && !ww.isVisible()) {
					    	ww.show();
					    } else {
					    	ww.toFront();
					    }
				}*/
				
				
			}
			
		   
		};
		//根据事件类型和事件中包含的数据，响应事件
		if(AppEvents.DESKTOP_SHORTCUT_ONCLICK==event.getType()){//根据事件类型，处理事件
			//根据事件中包含的数据，响应事件，即创建并初始化窗口
			
		//	this.createDynamicDesktop2(event);//最终创建出了桌面快捷方式（View视图）
			/**
			 * 何时添加控件的事件
			 * 1：创建控件的过程中，添加
			 * 识别GxtComponentMetaNodeModel中，Map中某个指，来设置它是否有AppEvent事件，
			 * 如何有AppEvent事件，需要被监听。
			 * 需要在Shortcut工厂中，通过ShortcutModelEnum.AppEven来判断，是否有事件需要监听
			 * 如果判断有，
			 * 根据Shortcut特定的方式，添加事件监听。如 Shortcut.addListener()
			 * 
			 * 2：控件创建完成后，添加
			 * 控件创建完成后，返回的是一个Desktop。
			 * 如何知道，改为哪个控件添加事件
			 */
			/**
			 * 为每个快捷方式，注册单击事件（包括业务事件）
			 */
			//List<Shortcut> list = desktop.getShortcuts();
			//list.get(0).
		}
	}
	/*private GxtComponentMetaModel getDesktopMetaModel_Shortcut() {
		Map<String, Object> map1=new HashMap<String, Object>();
		map1.put("component_model_type", ComponentTypeEnum.DESKTOP_MODEL);
		GxtComponentMetaNodeModel node1=new GxtComponentMetaNodeModel(map1, 1, 6);
		
		Map<String, Object> map2=new HashMap<String, Object>();
		map2.put("component_model_type", ComponentTypeEnum.SHORTCUT_MODEL);
		//TODO map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
		map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
		GxtComponentMetaNodeModel node2=new GxtComponentMetaNodeModel(map2, 2, 3);
		
		Map<String, Object> map3=new HashMap<String, Object>();
		map3.put("component_model_type", ComponentTypeEnum.SHORTCUT_MODEL);
		GxtComponentMetaNodeModel node3=new GxtComponentMetaNodeModel(map3, 4, 5);
		
		List<GxtComponentMetaNodeModel> list = new ArrayList<GxtComponentMetaNodeModel>();
		list.add(node1);
		list.add(node2);
		list.add(node3);
		GxtComponentMetaModel gxtComponentMetaModel = new GxtComponentMetaModel();
		gxtComponentMetaModel.setList(list);
		
		return gxtComponentMetaModel;
		
	}
	private GxtComponentMetaModel getDesktopMetaModel() {
		Map<String, Object> map1=new HashMap<String, Object>();
		map1.put("component_model_type", ComponentTypeEnum.DESKTOP_MODEL);
		GxtComponentMetaNodeModel node1=new GxtComponentMetaNodeModel(map1, 1, 6);
		
		Map<String, Object> map2=new HashMap<String, Object>();
		map2.put("component_model_type", ComponentTypeEnum.SHORTCUT_MODEL);
		//TODO map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
		map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
		GxtComponentMetaNodeModel node2=new GxtComponentMetaNodeModel(map2, 2, 3);
		
		Map<String, Object> map3=new HashMap<String, Object>();
		map3.put("component_model_type", ComponentTypeEnum.SHORTCUT_MODEL);
		GxtComponentMetaNodeModel node3=new GxtComponentMetaNodeModel(map3, 4, 5);
		
		List<GxtComponentMetaNodeModel> list = new ArrayList<GxtComponentMetaNodeModel>();
		list.add(node1);
		list.add(node2);
		list.add(node3);
		GxtComponentMetaModel gxtComponentMetaModel = new GxtComponentMetaModel();
		gxtComponentMetaModel.setList(list);
		
		return gxtComponentMetaModel;
		
	}
	
	*//**
	 * 模拟调用后台逻辑后，传回来的对象
	 *//*
	 private Window createGridWindow() {
		    Window w = new Window();
		    w.setIcon(IconHelper.createStyle("icon-grid"));
		    w.setMinimizable(true);
		    w.setMaximizable(true);
		    w.setHeading("Grid Window");
		    w.setSize(500, 400);
		    w.setLayout(new FitLayout());
		    
		    w.setId("999");

		    GroupingStore<Stock> store = new GroupingStore<Stock>();
		    store.add(TestData.getCompanies());
		    store.groupBy("industry");

		    ColumnConfig company = new ColumnConfig("name", "Company", 60);
		    ColumnConfig price = new ColumnConfig("open", "Price", 20);
		    price.setNumberFormat(NumberFormat.getCurrencyFormat());
		    ColumnConfig change = new ColumnConfig("change", "Change", 20);
		    ColumnConfig industry = new ColumnConfig("industry", "Industry", 20);
		    ColumnConfig last = new ColumnConfig("date", "Last Updated", 20);
		    last.setDateTimeFormat(DateTimeFormat.getFormat("MM/dd/y"));

		    List<ColumnConfig> config = new ArrayList<ColumnConfig>();
		    config.add(company);
		    config.add(price);
		    config.add(change);
		    config.add(industry);
		    config.add(last);

		    final ColumnModel cm = new ColumnModel(config);

		    GroupingView view = new GroupingView();
		    view.setForceFit(true);
		    view.setGroupRenderer(new GridGroupRenderer() {
		      public String render(GroupColumnData data) {
		        String f = cm.getColumnById(data.field).getHeader();
		        String l = data.models.size() == 1 ? "Item" : "Items";
		        return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";
		      }
		    });

		    Grid<Stock> grid = new Grid<Stock>(store, cm);
		    grid.setView(view);
		    grid.setBorders(true);

		    w.add(grid);
		    return w;
		  }
	 
	 *//**
		 * 模拟调用后台逻辑后，传回来的对象
		 *//*
		 private Window createGridWindow2() {
			    Window w = new Window();
			    w.setIcon(IconHelper.createStyle("icon-grid"));
			    w.setMinimizable(true);
			    w.setMaximizable(true);
			    w.setHeading("Grid Window222222");
			    w.setSize(500, 400);
			    w.setLayout(new FitLayout());

			    GroupingStore<Stock> store = new GroupingStore<Stock>();
			    store.add(TestData.getCompanies());
			    store.groupBy("industry");

			    ColumnConfig company = new ColumnConfig("name", "Company", 60);
			    ColumnConfig price = new ColumnConfig("open", "Price", 20);
			    price.setNumberFormat(NumberFormat.getCurrencyFormat());
			    ColumnConfig change = new ColumnConfig("change", "Change", 20);
			    ColumnConfig industry = new ColumnConfig("industry", "Industry", 20);
			    ColumnConfig last = new ColumnConfig("date", "Last Updated", 20);
			    last.setDateTimeFormat(DateTimeFormat.getFormat("MM/dd/y"));

			    List<ColumnConfig> config = new ArrayList<ColumnConfig>();
			    config.add(company);
			    config.add(price);
			    config.add(change);
			    config.add(industry);
			    config.add(last);

			    final ColumnModel cm = new ColumnModel(config);

			    GroupingView view = new GroupingView();
			    view.setForceFit(true);
			    view.setGroupRenderer(new GridGroupRenderer() {
			      public String render(GroupColumnData data) {
			        String f = cm.getColumnById(data.field).getHeader();
			        String l = data.models.size() == 1 ? "Item" : "Items";
			        return f + ": " + data.group + " (" + data.models.size() + " " + l + ")";
			      }
			    });

			    Grid<Stock> grid = new Grid<Stock>(store, cm);
			    grid.setView(view);
			    grid.setBorders(true);

			    w.add(grid);
			    return w;
			  }
		 
	 
	*//**
	 * 模拟从后台传过来的关于Shortcut控件的元模型信息
	 *//*
	private GxtComponentMetaNodeModel getGxtComponentMetaNodeModel2() {
		Map<String, Object> map2=new HashMap<String, Object>();
		map2.put("component_model_type", ComponentTypeEnum.SHORTCUT_MODEL);
		//TODO map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
		map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
			Map<String,Object> codes2 = new HashMap<String, Object>();
			//添加需要监听的事件类型，指定由某一个控制器响应，控制器内部应该如何响应（附加参数和数据）
			*//**
			 * 00_01_02为特征码
			 * 或者是 控制器的唯一标识
			 *//*
				Map<String,Object> subMap = new HashMap<String, Object>();
					EventStructureMetaModel eventStructureMetaModel = new EventStructureMetaModel();
					eventStructureMetaModel.setControllerId("shortcutController02");
					eventStructureMetaModel.setResponseModeId("00_02_02");
				subMap.put("eventstructuremetamodel", eventStructureMetaModel);
			codes2.put("0003", subMap);
			//codes1.add("0002");
		map2.put("registereventtypes", codes2);
		map2.put("text", "2222222222createWindow-----LoginView----AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER");	
		GxtComponentMetaNodeModel node2=new GxtComponentMetaNodeModel(map2);
		return node2;
	}
	
	*//**
	 * 模拟从后台传过来的关于Shortcut控件的元模型信息
	 *//*
	private GxtComponentMetaNodeModel getGxtComponentMetaNodeModel() {
		Map<String, Object> map2=new HashMap<String, Object>();
		map2.put("component_model_type", ComponentTypeEnum.SHORTCUT_MODEL);
		//TODO map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
		map2.put("appEventType", AppEvents.DESKTOP_SHORTCUT_ONCLICK_INIT);
			Map<String,Object> codes2 = new HashMap<String, Object>();
			//添加需要监听的事件类型，指定由某一个控制器响应，控制器内部应该如何响应（附加参数和数据）
			*//**
			 * 00_01_02为特征码
			 * 或者是 控制器的唯一标识
			 *//*
				Map<String,Object> subMap = new HashMap<String, Object>();
					EventStructureMetaModel eventStructureMetaModel = new EventStructureMetaModel();
					eventStructureMetaModel.setControllerId("shortcutController01");
					eventStructureMetaModel.setResponseModeId("00_01_02");
				subMap.put("eventstructuremetamodel", eventStructureMetaModel);
			codes2.put("0003", subMap);
			//codes1.add("0002");
		map2.put("registereventtypes", codes2);
		map2.put("text", "11111111111createWindow-----LoginView----AppEvents.DESKTOP_INIT_FOR_LOGGED_IN_USER");	
		GxtComponentMetaNodeModel node2=new GxtComponentMetaNodeModel(map2);
		return node2;
	}
	 
	private void itemSelected(ComponentEvent ce) {
	    Window w;
	    if (ce instanceof MenuEvent) {
	      MenuEvent me = (MenuEvent) ce;
	      w = me.getItem().getData("window");
	    } else {
	      w = ce.getComponent().getData("window");
	    }
	    if (!desktop.getWindows().contains(w)) {
	      desktop.addWindow(w);
	    }
	    if (w != null && !w.isVisible()) {
	      w.show();
	    } else {
	      w.toFront();
	    }
	    
	    
		
	    
	}*/

	@Override
	public void go(HasWidgets container) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void bind() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public BaseDisplay getDisplay() {
		// TODO Auto-generated method stub
		return this.display;
	}
}
